package com.masterrabbit.mcslf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.masterrabbit.mcslf.contans.Constants;
import com.masterrabbit.mcslf.exception.McslfException;
import com.masterrabbit.mcslf.pojo.Merchants;
import com.masterrabbit.mcslf.service.MerchantsService;
import com.masterrabbit.mcslf.mapper.MerchantsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
* @author hasee
* @description 针对表【merchants】的数据库操作Service实现
* @createDate 2025-03-18 19:35:48
*/
@Service
public class MerchantsServiceImpl extends ServiceImpl<MerchantsMapper, Merchants>
    implements MerchantsService{
    @Autowired
    MerchantsMapper merchantsMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public List<Merchants> getList(Merchants merchants){
       return merchantsMapper.selectMerchantsList(merchants);
    }

    @Override
    public void updataShopBalance(Integer merchantId, BigDecimal amount, String status) {
        Merchants merchants = merchantsMapper.selectById(merchantId);
        if (status.equals(Constants.INCREASE)){
//            被每日流水调用的时候加锁和线程池
            merchants.setShopBalance(merchants.getShopBalance().add(amount));
            merchants.setCumulativeIncome(merchants.getCumulativeIncome().add(amount));
            merchantsMapper.updateById(merchants);
        }
        if (status.equals(Constants.DECLINE)){
//            只需要加锁即可提现不会出现并发问题
            boolean flag = true;
            while (flag){
                while (flag){
                    flag =! redisTemplate.opsForValue().setIfAbsent(Constants.PAYOUE_LOCK+":"+merchants.getMerchantId(), 1);
                }
            }
            try {
                merchants.setShopBalance(merchants.getShopBalance().subtract(amount));
                merchants.setCumulativeWithdrawal(merchants.getCumulativeWithdrawal().add(amount));
                merchantsMapper.updateById(merchants);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                throw new RuntimeException(e);
            } finally {
                redisTemplate.delete(Constants.PAYOUE_LOCK+":"+merchants.getMerchantId());
            }
        }

    }
}




